﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace ToyundaPhone.Helpers
{
	public static class ListButtonVisibility
	{
		public static Database.Playlist GetPlaylist(DependencyObject obj)
		{
			return (Database.Playlist)obj.GetValue(PlaylistProperty);
		}

		public static void SetPlaylist(DependencyObject obj, Database.Playlist value)
		{
			obj.SetValue(PlaylistProperty, value);
		}

		public static readonly DependencyProperty PlaylistProperty =
			DependencyProperty.RegisterAttached("Playlist", typeof(Database.Playlist), typeof(Button), new PropertyMetadata(null, (sender, e) =>
			{
				UpdateVisibility(sender as Button, e.NewValue as Database.Playlist, GetIsAdd(sender));
			}));

		public static object GetTrigger(DependencyObject obj)
		{
			return (object)obj.GetValue(TriggerProperty);
		}

		public static void SetTrigger(DependencyObject obj, object value)
		{
			obj.SetValue(TriggerProperty, value);
		}

		// Using a DependencyProperty as the backing store for Trigger.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty TriggerProperty =
			DependencyProperty.RegisterAttached("Trigger", typeof(object), typeof(Button), new PropertyMetadata(null, (sender, e) =>
			{
				UpdateVisibility(sender as Button, GetPlaylist(sender), GetIsAdd(sender));
			}));

		public static bool GetIsAdd(DependencyObject obj)
		{
			return (bool)obj.GetValue(IsAddProperty);
		}

		public static void SetIsAdd(DependencyObject obj, bool value)
		{
			obj.SetValue(IsAddProperty, value);
		}

		// Using a DependencyProperty as the backing store for IsAdd.  This enables animation, styling, binding, etc...
		public static readonly DependencyProperty IsAddProperty =
			DependencyProperty.RegisterAttached("IsAdd", typeof(bool), typeof(Button), new PropertyMetadata(false, (sender, e) =>
			{
				UpdateVisibility(sender as Button, GetPlaylist(sender), (bool)e.NewValue);
			}));

		public static void UpdateVisibility(Button button, Database.Playlist playlist, bool isAdd)
		{
			Database.Song song = button.DataContext as Database.Song;
			Visibility visibility = (((playlist != null) && playlist.PlaylistSongs.Any(ps => ps.SongSong == song)) == isAdd) ? Visibility.Collapsed : Visibility.Visible;
			button.Visibility = visibility;
		}
	}
}
